package com.quan.wx.web.biz.controller.xczs;

import java.io.IOException;
import java.net.URLEncoder;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.quan.base.common.base.web.support.controller.BaseController;
import com.quan.weixin.WeixinConstant;
import com.quan.weixin.api.API;
import com.quan.weixin.api.OAuthAccessToken;
import com.quan.weixin.common.WeixinContext;
import com.quan.weixin.common.WeixinUtil;
import com.quan.weixin.model.UserDetail;
import com.quan.weixin.tools.WeiXinTools;
import com.quan.xczs.rpc.api.XczsUserService;
import com.quan.xczs.rpc.model.XczsUser;

/**
 * 注册用户，邀请朋友授权页面
 * @author yhaoquan
 *
 */
@RestController
@RequestMapping(value = "/wx/oauth/xczs/invite")
public class XczsOAuthInviteController extends BaseController {

	@Autowired
	private XczsUserService xczsUserService ;
	
	/**
	 * 静默授权
	 * @param state 用户携带的参数（可以是一个业务页面的URL地址）
	 */
	@GetMapping(value = "/oauth_process_base")
	public void oAuthProcessBase(String state) {
		logger.debug("邀请朋友-->微信网页静默授权----------------------");
		
		String callbackUrl = "http://"+WeixinConstant.WEIXIN_OAUTH_PAGE_URL+"/wx/oauth/xczs/invite/oauth_callback_base" ;
		
		//用户携带的参数
		if(!StringUtils.isNotBlank(state)) {
			state = "STATE" ;
		}
		
		//第一步：用户同意授权，获取code
		String getCodeUrl = API.get(API.OAUTH_CODE_URL, WeixinConstant.APPID, callbackUrl, "snsapi_base", state) ;
		
		try {
			this.response.sendRedirect(getCodeUrl);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 静默授权回调处理方法
	 * @return
	 */
	@GetMapping(value = "/oauth_callback_base")
	public void OAuthCallbackBase() {
		
		//接收微信传回的code参数
		String code = request.getParameter("code") ;
		
		try {
			//第二步：通过code换取网页授权access_token
			String getAccessTokenUrl = API.get(API.OAUTH_CODE_ACCESS_TOKEN_URL, WeixinConstant.APPID, WeixinConstant.APPSECRET, code) ;
			OAuthAccessToken oAuthAccessToken = WeixinUtil.doGet(getAccessTokenUrl).asBean(OAuthAccessToken.class) ;
			
			UserDetail userDetail = WeiXinTools.getUserDetail(WeixinContext.getAccessToken(), oAuthAccessToken.getOpenid()) ;
			logger.debug("获取用户信息==>NickName：{}, OPENID：{}", userDetail.getNickname(), userDetail.getOpenid());
			if(null != userDetail.getOpenid()) {
				//1：根据openid判断用户是否存在，不存在则记录当前用户到数据库
				XczsUser checkValue = this.xczsUserService.checkValue("openid", userDetail.getOpenid()) ;
				
				if(null == checkValue) {//用户不存在
					//保存用户信息
					XczsUser xczsUser = new XczsUser() ;
					BeanUtils.copyProperties(userDetail, xczsUser);
					xczsUser.setSubscribeTime(userDetail.getSubscribe_time());
					xczsUser.setTagidList(JSON.toJSONString(userDetail.getTagid_list()));
					xczsUser.setHeadimgurl(userDetail.getHeadimgurl() != null ? userDetail.getHeadimgurl().replaceAll("/132", "/46") : null);
					this.xczsUserService.insertSelective(xczsUser) ;
					
					logger.debug("数据库中不存在该用户信息，记录当前用户到数据库中，引导用户到绑定手机号注册页面，当前用户注册后才能邀请朋友");
					
					//2：引导用户到注册绑定手机号页面
					this.response.sendRedirect("http://"+WeixinConstant.WEIXIN_OAUTH_PAGE_URL+"/h5/xczs/biz/register.html?openid="+userDetail.getOpenid());
					
				} else { //用户已存在
					XczsUser user = this.xczsUserService.getUserByOpenId(userDetail.getOpenid()) ;
					
					//用户未绑定手机号码
					if(StringUtils.isBlank(user.getMobile())) { 
						logger.debug("数据库中已存在用户信息，但未绑定手机号，引导用户到绑定手机号注册页面，注册后才能邀请朋友");
						
						this.response.sendRedirect("http://"+WeixinConstant.WEIXIN_OAUTH_PAGE_URL+"/h5/xczs/biz/register.html?openid="+userDetail.getOpenid()+"&msg="+URLEncoder.encode("注册后才能邀请朋友", "utf-8"));
					} else {
						
						//当前用户已是注册用户，可以邀请朋友，跳转到我的二维码邀请朋友页面
						this.response.sendRedirect("http://"+WeixinConstant.WEIXIN_OAUTH_PAGE_URL+"/h5/xczs/biz/invite.html?openid="+userDetail.getOpenid()+"&mobile="+user.getMobile());
					}
					
				}
			} else {
				logger.error("微信网页授权获取用户信息失败：{}", userDetail);
				this.response.sendRedirect("http://"+WeixinConstant.WEIXIN_OAUTH_PAGE_URL+"/h5/xczs/biz/error.html?msg="+URLEncoder.encode("网页授权失败", "utf-8"));
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
}
